﻿#include "Shader.h"
#include "Misc.h"
#include "WinFunc.h"


namespace Base {

	Shader::Shader() {}
	Shader::~Shader() {}

	void Shader::Init(
		const std::string& hlslRelativeFileName,
		const std::string& vsEntry,
		const std::string& fsEntry) {

		auto graphics = Graphics::GetInstance();
		auto device = graphics->GetDevice();

		DWORD shaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
		shaderFlags |= D3DCOMPILE_DEBUG;
#endif

		// create vertex shader
		ComPtr<ID3DBlob> errorBuffer;
		D_HRESULT(D3DCompileFromFile(
			WinFunc::StrToWstr(hlslRelativeFileName).c_str(),
			nullptr,	// pDefines
			nullptr,    // pInclude
			vsEntry.c_str(),  // pEntrypoint
			"vs_4_0",   // pTarget
			shaderFlags, // Flags1
			0,			 // Flags2
			&m_vsBuffer,   // ppCode
			&errorBuffer // ppErrorMsgs
		));
		if (errorBuffer != nullptr) {
			auto msg = reinterpret_cast<char*>(errorBuffer->GetBufferPointer());
			Debug::ThrowOrMessageBox(msg);
		}
		D_HRESULT(device->CreateVertexShader(
			m_vsBuffer->GetBufferPointer(),
			m_vsBuffer->GetBufferSize(),
			0,
			&m_vertexShader
		));


		// create pixel shader
		// 创建像素着色器
		D_HRESULT(D3DCompileFromFile(
			WinFunc::StrToWstr(hlslRelativeFileName).c_str(),
			nullptr,
			nullptr,
			fsEntry.c_str(),
			"ps_4_0",
			shaderFlags,
			0,
			&m_psBuffer,
			&errorBuffer
		));
		if (errorBuffer != nullptr)
		{
			auto msg = reinterpret_cast<char*>(errorBuffer->GetBufferPointer());
			Debug::ThrowOrMessageBox(msg);
		}
		D_HRESULT(device->CreatePixelShader(
			m_psBuffer->GetBufferPointer(),
			m_psBuffer->GetBufferSize(),
			0,
			&m_pixelShader));
	}
}